﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;

public class DllLoader : MonoBehaviour
{
    private string str;
    string url;
    // Use this for initialization
    IEnumerator Start()
    {
        if (Application.platform == RuntimePlatform.WindowsEditor)
        {
            url = @"file://" + Application.dataPath + "/Dll/myassets.android";
        }
        else if (Application.platform == RuntimePlatform.Android)
        {
            url = Application.streamingAssetsPath + "/myassets.android";
        }
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
            url = Application.streamingAssetsPath + "/myassets.iphone";
        }

        Debug.Log("url: " + url);
        WWW www = new WWW(url);

        yield return www;
        yield return new WaitForSeconds(1);

        if (www.error != null)
        {
            Debug.Log("加载 出错");
        }

        if (www.isDone)
        {
            Debug.Log("加载完毕");
            AssetBundle ab = www.assetBundle;

            try
            {
                //先把DLL以TextAsset类型取出来,在把bytes给Assembly.Load方法读取准备进入反射操作
                Assembly aly = System.Reflection.Assembly.Load(((TextAsset)www.assetBundle.mainAsset).bytes);

                //获取DLL下全部的类型
                foreach (var i in aly.GetTypes())
                {
                    //调试代码
                    Debug.Log(i.Name);
                    str += "\r\n" + i.Name;

                    //添加组件到当前GameObject下面
                    Component c = this.gameObject.AddComponent(i);

                    //然后类名是MyClass,就把文本引用赋值给MyClass.platefaceText属性.
                    if (i.Name == "MyClass")
                    {

                        //FieldInfo info = c.GetType().GetField("platefaceText");
                        //info.SetValue(c, myAgeText);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.Log("加载DLL出错");
                Debug.Log(e.Message);
            }
        }
    }
}
